package com.dlc.shop.systemtest.util;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.Json;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author lanhai
 */
@Slf4j
public class CheckUtil {




    public static void check(HttpResponse response) {
        String body = getBody(response);
        ServerResponseEntity serverResponseEntity = Json.parseObject(body, ServerResponseEntity.class);
        if (!serverResponseEntity.isSuccess()) {
            throw new RuntimeException(serverResponseEntity.getMsg());
        }
    }

    public static <T>  T checkAndGetObject(HttpResponse response, Class<T> clazz) {
        String body = getBody(response);
        TypeReference<ServerResponseEntity<T>> typeReference = new TypeReference<ServerResponseEntity<T>>(clazz) {};
        ServerResponseEntity<T> serverResponseEntity = JSON.parseObject(body, typeReference);
        if (!serverResponseEntity.isSuccess()) {
            throw new RuntimeException(serverResponseEntity.getMsg());
        }
        return serverResponseEntity.getData();
    }

    public static <T> List<T> checkAndGetArray(HttpResponse response, Class<T[]> clazz) {
        String body = getBody(response);
        ServerResponseEntity<T> serverResponseEntity = Json.parseObject(body, ServerResponseEntity.class);
        if (!serverResponseEntity.isSuccess()) {
            throw new RuntimeException(serverResponseEntity.getMsg());
        }
        return Json.parseArray(Json.toJsonString(serverResponseEntity.getData()), clazz);
    }

    public static <T>  String  checkAndGetObjects(HttpResponse response) {
        String body = getBody(response);
        JSONObject jsonObject = JSON.parseObject(body);
        JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
        return data.get("records").toString();
    }

    private static String getBody(HttpResponse response){
        if (!response.isOk()) {
            log.info("response: {}",response);
            throw new RuntimeException("请求异常");
        }
        System.out.println(response.body());
        return response.body();
    }
}
